import { App } from "vue";
import version from "./version";

type ComponentType = any;

export interface HzUiInstance {
  version: string;
  componentPrefix: string;
  install(app: App): void;
}

interface HzUiCreateOptions {
  componentPrefix?: string;
  components: ComponentType[];
}

function create({ componentPrefix = "Hz", components = [] }: HzUiCreateOptions): HzUiInstance {
  const installTargets: App[] = [];

  const registerComponent = (app: App, name: string, component: any) => {
    const registered = app.component(componentPrefix + name);
    if (!registered) {
      app.component(componentPrefix + name, component);
    }
  };

  function install(app: App): void {
    if (installTargets.includes(app)) return;

    installTargets.push(app);

    components.forEach((component) => {
      const { name, alias } = component;
      registerComponent(app, name, component);

      if (alias) {
        alias.forEach((aliasName: string) => {
          registerComponent(app, aliasName, component);
        });
      }
    });
  }

  return {
    version,
    componentPrefix,
    install,
  };
}

export default create;
